package org.lzy.pt;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.jivesoftware.database.DbConnectionManager;
import org.lzy.pt.bean.Contact;

public class ContactManager {

	private String LOAD_CONTACT = "select * from oftContacts LIMIT ?,? ";
	
	private static ContactManager contactManager = new ContactManager();
	
	private static final String CONTACT_COUNT = "SELECT count(*) FROM oftContacts";
	
	private ContactManager() {
	}
	
	public static ContactManager getInstance(){
		return contactManager;
	}
	
	public List<Contact> getContactList(int startIndex, int numResults) throws SQLException {
    	QueryRunner runner = new QueryRunner();
    	Connection connection = DbConnectionManager.getConnection();
    	List<Contact> result = runner.query(connection,LOAD_CONTACT, new BeanListHandler<Contact>(Contact.class),
    			new Object[]{startIndex,numResults});
    	DbConnectionManager.closeConnection(connection);
    	return result;
	}
	
	public long getCount() {
		Connection connection = null;
		long result = 0 ;
		try {
			QueryRunner runner = new QueryRunner();
			connection = DbConnectionManager.getConnection();
			result = (Long) runner.query(connection, CONTACT_COUNT,new ScalarHandler());
		} catch (SQLException e) {
		} finally {
			DbConnectionManager.closeConnection(connection);
		}
		return result;
	}
	
	
	
}
